<?php

namespace App\Services;

use App\Models\GoodsCart;
use App\Models\GoodsSku;


class GoodsCartService extends BaseService
{
    /**
     * 购物车是否存在商品
     * @return
     */
    public function goodsCart($sku_id,$users_id) {
        return GoodsCart::where('sku_id',$sku_id)->where('users_id',$users_id)->first();
    }
    /**
     * 获取购物车列表
     * @return
     */
    public function list($users_id,$ids = null) {
        $goodsCartList =  GoodsCart::where('users_id',$users_id)
            ->select('id','sku_id','title','image','users_id','num');
        if($ids){
            $goodsCartList->whereIn('sku_id',$ids);
        }

        $goodsCartList = $goodsCartList->get();
        if(count($goodsCartList) < 1){
            return [];
        }
        $skuIds = $goodsCartList->pluck('sku_id');
        $goodsSku = GoodsSku::whereIn('id',$skuIds)->get()->toArray();
        $goodsSkuPriceValIds = array_column($goodsSku,'price','id');

        $skuSpecsValueIds = array_column($goodsSku,'goods_specs_value_id','id');
        $skuGoodsIds = array_column($goodsSku,'goods_id','id');
        $specsValues = GoodsSpecsService::getInstance()->dealSpecsVal($skuSpecsValueIds);
        $stock = array_column($goodsSku,'stock','id'); //库存

        foreach ($goodsCartList as $k=>$v){
            $price = $goodsSkuPriceValIds[$v->sku_id]?? '';

            if($ids && isset($stock[$v->sku_id]) && $stock[$v->sku_id] < $v->num){
                return [false,$v->title.'商品库存不足'];
            }
            $goodsCartList[$k]['price'] = $price;

            if($price>0 && $v->num>0){
                $goodsCartList[$k]['total_price'] = $price*$v->num;
            }

            $goodsCartList[$k]['sku'] = $specsValues[$v->sku_id] ?? '暂无规则';
            $goodsCartList[$k]['goods_id'] = $skuGoodsIds[$v->sku_id];
        }

        return $goodsCartList;
    }
}
